from pathlib import Path
import random
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

IMAGE_DIR = Path(__file__).parent / "static" / "images"
used_images = []

app.mount(
    "/backend_api/static",
    StaticFiles(directory=Path(__file__).parent / "static"),
    name="static",
)

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/random_images")
async def get_random_images(request: Request):
    global used_images

    image_files = [
        f for f in IMAGE_DIR.iterdir()
        if f.suffix.lower() in [".png", ".jpg", ".jpeg", ".webp", ".avif", ".gif"]
    ]

    # 重置已使用列表
    if len(used_images) >= len(image_files):
        used_images = []

    # 过滤未用过的图片
    available_images = [img for img in image_files if img not in used_images]
    if not available_images:
        return JSONResponse({"message": [], "has_more": False, "status": "success"})

    # 随机选最多10张
    num_to_select = min(10, len(available_images))
    selected = random.sample(available_images, num_to_select)

    used_images.extend(selected)

    base_url = str(request.base_url)
    urls = [
        (base_url + str(img.relative_to(Path(__file__).parent.parent)).replace("\\", "/"))
        for img in selected
    ]

    has_more = len(used_images) < len(image_files)

    return JSONResponse({
        "message": urls,
        "has_more": has_more,
        "status": "success"
    })
